<template>
  <base-breadcrumb :title="$route.meta.title">
    <a-form-model ref="ruleForm" :model="form" :label-col="{ span: 6 }" :wrapper-col="{ span: 18 }"
                  id="base-breadcrumb" style="position: relative"
                  :rules="editModel !==0 ? rules : {}">
      <a-spin :spinning="loading">
        <!-- 表单基础信息 -->
        <a-card>
          <equipment-base-form-module :form="form" :editModel="editModel" :isOwn="isOwn"
                                      @clearData="clearData" @hanleOrgSelect="hanleOrgSelect">
          </equipment-base-form-module>
        </a-card>
        <!-- 设备调拨记录 -->
        <allocation-record-module v-if="isShowAllotRecord" :queryParam="{mdOwnId:id}">
        </allocation-record-module>
        <!-- 计量设备检定记录 -->
        <equipment-verification-record-module v-if="isShowVerifRecord" :queryParam="{mdOwnId:id}">
        </equipment-verification-record-module>
      </a-spin>
      <!-- 页脚操作栏 -->
      <div class="btn_box page-btn-right-top">
        <a-button :loading="loading" :disabled="loading" v-if="editModel == 1 || editModel == 2"
                  type="primary" class="button_right" @click="handleSubmit">提交</a-button>
        <a-button type="primary" @click="closePage">关闭</a-button>
      </div>
    </a-form-model>
  </base-breadcrumb>
</template>

<script>
import BaseEditPage from '@/views/baseEditPage' // 编辑详情页基础配置
import api from '@/api/quality/ownEquipmentLedger' // api
import equipmentBaseFormModule from '@/views/quality/equipmentManagement/module/equipmentBaseForm/index'
import allocationRecordModule from '@/views/quality/equipmentManagement/module/allocationRecord/index'
import equipmentVerificationRecordModule from '@/views/quality/equipmentManagement/module/equipmentVerificationRecord/index'
let { currentPost } = JSON.parse(sessionStorage.getItem('ycloud-user_info'));
//自定义验证规格
const validatorVerificationPeriod = (rule, value, callback) => {
  if (!value) {
    callback(new Error('请输入检定周期（月数）'))
  } else {
    if (!/^[1-9]\d*$/.test(value)) {
      callback(new Error('请输入正整数'))
    } else {
      callback()
    }
  }
}
export default {
  name: "ownEquipmentLedgerInfo",
  extends: new BaseEditPage(),
  components: {
    equipmentBaseFormModule,
    allocationRecordModule,
    equipmentVerificationRecordModule,
  },
  data() {
    return {
      loading: false,
      form: {},
      api, // api
      id: this.$route.query && this.$route.query.id ? this.$route.query.id : null,
      isOwn: this.$route.query.isOwn ? true : false,//true:自有,false:项目分包
      editModel: this.$route.query.editModel,//页面标识
      isShowAllotRecord: this.$route.query.isShowAllotRecord ? true : false,//是否展示调拨记录
      isShowVerifRecord: this.$route.query.isShowVerifRecord ? true : false,//是否展示计量设备检定记录
    }
  },
  computed: {
    rules() {
      return {
        branchCompanyId: this.editModel == 2 && currentPost.code != 'BC' ? [{ required: true, message: '请选择所属单位', trigger: 'change' }] : [],
        mdId: this.editModel == 2 ? [{ required: true, message: '请选择设备名称', trigger: 'change' }] : [],
        mdModelId: this.editModel == 2 ? [{ required: true, message: '请选择规格型号', trigger: 'change' }] : [],
        mdClassify: this.editModel == 2 || this.editModel == 1 ? [{ required: true, message: '请选择设备分类', trigger: 'change' }] : [],
        purpose: this.editModel == 2 || this.editModel == 1 ? [{ required: true, message: '请输入设备用途', trigger: 'change' }] : [],
        appraisalType: this.editModel == 2 || this.editModel == 1 ? [{ required: true, message: '请选择检定方式', trigger: 'change' }] : [],
        beforeAppraisalDate: this.editModel == 2 || this.editModel == 1 ? [{ required: true, message: '请选择上次检定时间', trigger: 'change' }] : [],
        appraisalCycle: this.editModel == 2 || this.editModel == 1 ? [{ required: true, validator: validatorVerificationPeriod, trigger: 'change' }] : [],
        appraisalStatus: this.editModel == 2 || this.editModel == 1 ? [{ required: true, message: '请选择检定状态', trigger: 'change' }] : [],
        // materialCode: this.editModel == 2 || this.editModel == 1 ? [{ pattern: /^\d*$/, message: '只能输入整数', trigger: 'change' }] : [],
        // manufacturerCode: this.editModel == 2 || this.editModel == 1 ? [{ pattern: /^\d*$/, message: '只能输入整数', trigger: 'change' }] : [],
      }
    }
  },
  mounted() {
    this.initData();
  },
  methods: {
    /**
     * @description: 设置默认展示数据
     */
    initData() {
      if (this.editModel == 2) {
        const userInfo = this.$userInfo()
        this.form.mdStatus = '0';
        this.form.mdBelongTo = 'OWN';
        this.form.createTime = this.$dateFormat(new Date(), 'D');
        this.form.creatorId = userInfo.id;
        this.form.creatorName = userInfo.name;
      } else {
        this.getDatail();
      }
    },
    /**
     * @description: 选择所属单位
     * @param {String} val 选中的值
     */
    hanleOrgSelect(val) {
      this.$set(this.form, "mdCode", val);
    },
    /**
     * @description: 获取详情
     */
    async getDatail() {
      this.loading = true;
      let res = await this.api.getDetail({ id: this.id })
      this.loading = false;
      if (res.code === '0') {
        this.form = res.data;
      }
    },
    /**
     * @description: 提交表单
     */
    handleSubmit() {
      let that = this;
      let name = ['edit', 'create'][that.editModel - 1] // 根据操作切换url地址
      that.$refs.ruleForm.validate((e) => {
        if (e) {
          let _params = { ...that.form }
          // 格式化文件列表
          if (_params.ownPicFileList && _params.ownPicFileList.length) {
            _params.picFileIds = _params.ownPicFileList.map((item) => item.commonId);
          } else {
            _params.picFileIds = [];
          }
          if (_params.ownAnnexFileList && _params.ownAnnexFileList.length) {
            _params.annexFileIds = _params.ownAnnexFileList.map((item) => item.commonId);
          } else {
            _params.annexFileIds = [];
          }
          //数据处理
          if (_params.afterAppraisalDate) _params.afterAppraisalDate = _params.afterAppraisalDate + ' 00:00:00'
          if (_params.createTime) _params.createTime = _params.createTime + ' 00:00:00'
          if (_params.beforeAppraisalDate) _params.beforeAppraisalDate = _params.beforeAppraisalDate + ' 00:00:00'
          if (_params.appraisalCycle) { _params.appraisalCycle = parseInt(_params.appraisalCycle) }
          delete _params.ownPicFileList;
          delete _params.ownAnnexFileList;
          //发送请求
          that.loading = true;
          that.api[name](_params).then((res) => {
            that.loading = false;
            if (res.code === '0' || res.data.code === '0') {
              that.$message.success(['编辑', '添加'][that.editModel - 1] + '成功！')
              that.$multiTab.close()
            } else {
              that.$message.warning(['编辑', '添加'][that.editModel - 1] + '失败！')
            }
          }).catch((err) => {
            that.loading = false;
          })
        } else {
          that.$message.warning('请填写完所有必填项信息')
        }
      })
    },
    /**
     * @description: 清除表单数据
     * @param arr:指定字段
     */
    clearData(arr) {
      if (arr && arr.length) {
        arr.forEach((v) => {
          this.$set(this.form, v, undefined)
        })
      }
    },
    /**
     * @description: 关闭处理
     */
    closePage() {
      // 存在业务ID。则返回到调拨处理页面
      if (this.$route.query.businessId) {
        this.$router.push({
          path: '/matters/allocate/allocateHandle',
          query: {
            businessId: this.$route.query.businessId,
            id: this.$route.query.waitRecordId,
          }
        })
      } else {
        this.$multiTab.close()
      }
    },
  }
}
</script>

<style>
</style>